package com.swufe.team;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RateActivity extends AppCompatActivity implements Runnable{
    private static final String TAG = "Rate";
    private float dollarRate =0.12f;
    private float euroRate=0.14f;
    private float wonRate=120f;
    private String time;
    private String p_time;
    private String new_time;
    Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rate);

        SharedPreferences sharedPreferences=getSharedPreferences("myrate",RateActivity.MODE_PRIVATE);

        PreferenceManager.getDefaultSharedPreferences(this);
        dollarRate=sharedPreferences.getFloat("dollar_rate",0.12f);
        euroRate=sharedPreferences.getFloat("euro_rate",0.23f);
        wonRate=sharedPreferences.getFloat("won_rate",120f);
        dollarRate=sharedPreferences.getFloat("web_dollar",0.12f);
        euroRate=sharedPreferences.getFloat("web_euro",0.23f);
        wonRate=sharedPreferences.getFloat("web_won",120f);
        time=sharedPreferences.getString("time","20220414");
        String regEx="[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(time);
        p_time=m.replaceAll("").trim().toString().substring(0,7);

        Thread t=new Thread(this);
        t.start();
        handler=new Handler(Looper.myLooper()){
            @Override
            public void handleMessage(@NonNull Message msg) {
                if(msg.what==5){
                    Bundle bundle=(Bundle) msg.obj;
                    time=bundle.getString("time");
                    String regEx="[^0-9]";
                    Pattern p = Pattern.compile(regEx);
                    Matcher m = p.matcher(time);
                    new_time=m.replaceAll("").trim().toString().substring(0,7);

                if(new_time!=p_time){
                    dollarRate=bundle.getFloat("web-dollar");
                    euroRate=bundle.getFloat("web-euro");
                    wonRate=bundle.getFloat("web-won");
                    Toast.makeText(RateActivity.this, "汇率已更新", Toast.LENGTH_SHORT).show();}
           }
                super.handleMessage(msg);
            }
        };

    }

    public void click(View btn) {
        Log.i(TAG, "click:");

        EditText input = findViewById(R.id.rmb);
        String str = input.getText().toString();
        if (str.length() == 0) {
            Toast.makeText(this, "请输入数据", Toast.LENGTH_SHORT).show();
        } else {
            Log.i(TAG, "click:str=" + str);
            float inp = Float.parseFloat(str);
            float r = 0.0f;
            if (btn.getId() == R.id.btn_dollar) {
                r = inp * dollarRate;
            } else if (btn.getId() == R.id.btn_euro) {
                r = inp * euroRate;
            } else if (btn.getId() == R.id.btn_won) {
                r = inp * wonRate;
            }
            TextView result = findViewById(R.id.result);
            result.setText("兑换：" + r);
        }

    }
    public void open(View btn){
        Log.i(TAG, "open");

        Intent config = new Intent(this, com.swufe.team.config.class);
        config.putExtra("dollar_key", dollarRate);
        config.putExtra("euro_key", euroRate);
        config.putExtra("won_key", wonRate);
        startActivityForResult(config,3);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { //requestCode区分返回的页面，resultCode区分同一个页面返回不同的内容
        if (requestCode==3&&resultCode==6){
            Bundle bundle=data.getExtras();

            dollarRate=bundle.getFloat("key_dollar");
            euroRate=bundle.getFloat("key_euro");
            wonRate=bundle.getFloat("key_won");

            SharedPreferences sp =getSharedPreferences("myrate",RateActivity.MODE_PRIVATE);

            SharedPreferences.Editor editor=sp.edit();
            editor.putFloat("dollar_rate",dollarRate);
            editor.putFloat("euro_rate",euroRate);
            editor.putFloat("won_rate",wonRate);
            editor.apply();

        }
        super.onActivityResult(requestCode,resultCode,data);
    }
    public void run(){
        Log.i(TAG,"run :run()......");
        for(int i=1;i<3;i++) {
            Log.i(TAG,"run :i="+i);
            try {
                Thread.sleep(2000);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }



//        URL url= null;
//        try {
//            url = new URL("https://www.boc.cn/sourcedb/whpj/");
//            HttpURLConnection http= (HttpURLConnection) url.openConnection();
//            InputStream in =http.getInputStream();
//
//            String html=inputStream2String(in);
//            Log.i(TAG,"run: html="+html);
//
//        } catch (MalformedURLException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        Bundle retBundle=new Bundle();
        try {
            Document doc = Jsoup.connect("https://www.usd-cny.com/bankofchina.htm").get();
            Log.i(TAG,"run:"+"title="+doc.title());
            Element table= doc.getElementsByTag("table").first();

            Element tddollar=table.selectFirst("tr:nth-child(27) > td:nth-child(6)");
            Element tdeuro=table.selectFirst("tr:nth-child(8) > td:nth-child(6)");
            Element tdwon=table.selectFirst("tr:nth-child(14) > td:nth-child(6)");

            Element time= doc.selectFirst("body > section > div > div > article > p");
            Log.i(TAG, "run: time="+time.text());
            Log.i(TAG, "run: dollar="+tddollar.text());
            Log.i(TAG, "run: euro="+tdeuro.text());
            Log.i(TAG, "run: won="+tdwon.text());
            retBundle.putFloat("web-dollar",100f/Float.parseFloat(tddollar.text()));
            retBundle.putFloat("web-euro",100f/Float.parseFloat(tdeuro.text()));
            retBundle.putFloat("web-won",100f/Float.parseFloat(tdwon.text()));
            retBundle.putString("time",time.text());



//           Log.i(TAG, "run: table="+table);

//            Elements trs=doc.getElementsByTag("tr");
//            for (Element tr:trs ) {
//                Elements tds=tr.getElementsByTag("td");
//                if(tds.size()>0) {
//                    Element td1 = tds.first();
//                    Element td2 = tds.get(5);
//                    Log.i(TAG, "run: " + td1.text() + "==>" + td2.text());
//                }
//            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        Message msg=handler.obtainMessage(5);
//        msg.obj="Hello from msg";
        msg.obj=retBundle;
        handler.sendMessage(msg);

        SharedPreferences sp =getSharedPreferences("myrate",RateActivity.MODE_PRIVATE);

        SharedPreferences.Editor editor=sp.edit();
        editor.putFloat("web_dollar",dollarRate);
        editor.putFloat("web_euro",euroRate);
        editor.putFloat("web_won",wonRate);
        editor.putString("time",time);
        editor.apply();

        Log.i(TAG, "run: sendMessage bundle...");




    }
    private String inputStream2String(InputStream inputStream) throws IOException {
        final  int bufferSize=1024;
        final  char[] buffer = new char[bufferSize];
        final  StringBuffer out =new StringBuffer();
        Reader in =new InputStreamReader(inputStream,"UTF-8");
        while (true){
            int rsz =in.read(buffer,0,buffer.length);
            if(rsz<0)
                break;
            out.append(buffer,0,rsz);
        }
        return out.toString();
    }
}